package com.H1023.controller;

import com.H1023.pojo.Pager;
import com.H1023.pojo.Type;
import com.H1023.service.TypeService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author MJ
 * @date 2021/10/12 18:54
 */

@Controller
@RequestMapping("/type")
public class TypeController {

    @Autowired
    @Qualifier("typeServiceImpl")
    private TypeService typeService;

    //刷新页面  返回json数据
    // finished
    @RequestMapping("/allType")
    public String list(Model model) {
        Pager<Type> byPager = typeService.findByPager(1, 5);
        byPager.setTotal(typeService.count());
        model.addAttribute("list", byPager.getRows());
        model.addAttribute("count",typeService.count());
        return "allType";
    }

    //finish
    @RequestMapping("/addType")
    public String addType(String addname) {
        System.out.println("this is "+addname);
        int i = typeService.addType(new Type(addname));
        if (i==-1) //失败  重名或者其他异常
            return "failed";
        else
            return "success";
    }
    /*
method:待排序的字段
order:asc or desc
size: size number
page: page number
 */
    //所有的排序操作
    @RequestMapping("/page/{method}/{order}/{page}/{size}")
    @ResponseBody
    public String pager(@PathVariable String method,
                        @PathVariable String order,
                        @PathVariable int size,
                        @PathVariable int page){

        System.out.println("调用了pager方法！！！！");

        Pager<Type> byPager = typeService.findByPager(method, order, page, size);
        System.out.println(JSON.toJSONString(byPager));
        return JSON.toJSONString(byPager);

    }

    @RequestMapping("/del/{typeid}")
    public String deleteType(@PathVariable int typeid){
        System.out.println("this is "+typeid);
        int i = typeService.deleteType(typeid);
        if (i==-1) //失败  重名或者其他异常
            return "failed";
        else
            return "success";
    }

    @RequestMapping("/edit/{typeid}")
    public String toEditReader(@PathVariable int typeid, Model model){
        Type type = typeService.getTypeById(typeid);
        model.addAttribute("reader",type);
        return "editType";
    }

    @RequestMapping("/edit")
    public String editType(Type type){
        System.out.println("this is typeid:"+type.getTypeid()+"   this is typename:"+type.getTypename());
        int i = typeService.updateType(type.getTypeid(),type.getTypename());
        if (i==-1) //失败  重名或者其他异常
            return "failed";
        else
            return "success";
    }
}
